﻿//匿名函数
(function($,ajax, a) {
    //序列化不包含空值
    $.fn.serializeObject = function() {
        var b = {};
        $.each(this.serializeArray(), function(d, e) {
            var f = e.name,
            c = e.value;
            if(c!=''){
            	b[f] = b[f] === a ? c: $.isArray(b[f]) ? b[f].concat(c) : [b[f], c];
            }
        });
        return b;
    }
    var rcheckableType = ( /^(?:checkbox|radio)$/i );
    var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;
    $.fn.serializeQueryForm=function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} )
		.filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} )
		.map( function( i, elem ) {
			var val = jQuery( this ).val();
			console.log(jQuery( this ));
			console.log(elem);
			console.log(jQuery( this ).data("operator"))
			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
    $.query={
   		 get(search,key){
   			 if (key==a){
   				 key=search;
   				 search=window.location.search;
   			 }
   			 let p = search.substring(search.indexOf("?") + 1);
   			 var vars = p.split("&");
   			 for (var i=0;i<vars.length;i++) {
   				 var pair = vars[i].split("=");
   				 if(pair[0] == key){
   					 return decodeURIComponent(pair[1]);
   				 }
   			 }
   			 return "";
   		 }
   	}
    /*$.util2={
    		//浮点数加法运算  
    	floatAdd:function(arg1,arg2){
    		arg1=arg1||"0.00";
    	  	arg2=arg2||"0.00";
    	      var r1,r2,m;   
    	      var arg1s=arg1.toString();
    	      var arg2s=arg2.toString();
    	      try{r1=arg1s.split(".")[1].length;}catch(e){arg1s=arg1s+".00";r1=arg1s.split(".")[1].length;}
    	      try{r2=arg2s.split(".")[1].length;}catch(e){arg2s=arg2s+".00";r2=arg2s.split(".")[1].length;}
    	      for(var i=r1;i<Math.max(r1,r2);i++){
    	      	arg1s=arg1s+"0";
    	      }
    	      for(var i=r2;i<Math.max(r1,r2);i++){
    	      	arg2s=arg2s+"0";
    	      }
    	      m=Math.pow(10,Math.max(r1,r2));
    	      var a1=Number(arg1s.replace(".",""));  
    	      var a2=Number(arg2s.replace(".",""));  
    	      return (a1+a2)/m;
    	},
    	//浮点数减法运算   
    	floatSub:function(arg1,arg2){
    	  	arg1=arg1||"0.00";
    	  	arg2=arg2||"0.00";
    	      var r1,r2,m,n;   
    	      var arg1s=arg1.toString();
    	      var arg2s=arg2.toString();
    	      try{r1=arg1s.split(".")[1].length;}catch(e){arg1s=arg1s+".00";r1=arg1s.split(".")[1].length;}
    	      try{r2=arg2s.split(".")[1].length;}catch(e){arg2s=arg2s+".00";r2=arg2s.split(".")[1].length;}
    	      for(var i=r1;i<Math.max(r1,r2);i++){
    	      	arg1s=arg1s+"0";
    	      }
    	      for(var i=r2;i<Math.max(r1,r2);i++){
    	      	arg2s=arg2s+"0";
    	      }
    	      m=Math.pow(10,Math.max(r1,r2));   
    	      //动态控制精度长度   
    	      var a1=Number(arg1s.toString().replace(".",""));  
    	      var a2=Number(arg2s.toString().replace(".",""));  
    	      return (a1-a2)/m;   
    	  },
    	//浮点数乘法运算
    	  floatMul:function(arg1,arg2){
    	  	arg1=arg1||"0.00";
    	  	arg2=arg2||"0.00";
    	      var m=0,s1=arg1.toString(),s2=arg2.toString();   
    	      try{m+=s1.split(".")[1].length;}catch(e){}   
    	      try{m+=s2.split(".")[1].length;}catch(e){}   
    	      return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
    	  },
    	//浮点数除法运算
    	 floatDiv:function(arg1,arg2){
    		    var t1=0,t2=0,r1,r2;   
    		    try{t1=arg1.toString().split(".")[1].length;}catch(e){}   
    		    try{t2=arg2.toString().split(".")[1].length;}catch(e){}   
    		    with(Math){   
    		        r1=Number(arg1.toString().replace(".",""));  
    		        r2=Number(arg2.toString().replace(".",""));  
    		        return (r1/r2)*pow(10,t2-t1);
    		    }   
    	 },
    	 isFloat:function(v){
    			var reg=new RegExp("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[0-9][0-9]*))$");
    			return reg.test(v);
    	 },
    	 isMoney:function(floatvar){
    			var amt=parseFloat(floatvar);
    			var strAmt=amt.toString();
    			var posFloat=strAmt.indexOf('.');
    			if(strAmt.length<=(posFloat+3)||posFloat==-1){
    				return true;
    			}else{
    				return false;
    			}
    	 }
    }*/
    const ajaxProxy=function(options) {
		var successCallback = options.success;
	    var errorCallback = options.error;
	    
		options.success = function (result, textStatus, jqXHR) {
			//console.log(result);
			successCallback && successCallback(result);
		};
		options.error = function(XMLHttpRequest, textStatus){
    		//console.log(XMLHttpRequest);
    		let statusCode=XMLHttpRequest.status;
    		if(statusCode==401){
    			let refresh_token=localStorage.getItem("refresh_token");
    			if(refresh_token){
    				$.post("/refresh_token",{"refresh_token":refresh_token},function(result){
    					if(result.success){
    						$.ajax(options);
    					}else{
    						alert("认证已过期请重新登录");
    						var url=XMLHttpRequest.getResponseHeader("Redirect-URL");
    						if(url){
    							if(window.parent){
        		    				window.parent.location.replace(url);
        	    				}else{
        		    				window.location.replace(url);
        	    				}
    						}
    					}
    		    	});
    			}else{
    				var url=XMLHttpRequest.getResponseHeader("Redirect-URL");
    				if(url){
    					if(window.parent){
    	    				window.parent.location.replace(url);
        				}else{
    	    				window.location.replace(url);
        				}
    				}
    			}
    		}else{
    			if(XMLHttpRequest.responseText&&XMLHttpRequest.responseJSON){
    				alert(XMLHttpRequest.responseJSON.message);
    			}else{
    				alert(XMLHttpRequest.statusText);
    			}
    		}
    	}
		var completeCallback = options.complete;
	    options.complete = function(XMLHttpRequest,textStatus){
    		let Authorization=XMLHttpRequest.getResponseHeader("Authorization");
    		if(Authorization){
    			let AuthorizationObj=JSON.parse(Authorization);
    			let refresh_token=AuthorizationObj.refresh_token;
    			let access_token=AuthorizationObj.access_token;
    			localStorage.setItem("access_token", access_token);
    			if(refresh_token){
    				localStorage.setItem("refresh_token", refresh_token);
    			}
    		}
    		completeCallback && completeCallback(XMLHttpRequest,textStatus);
    	}
	    var beforeSendCallback = options.beforeSend;
	    options.beforeSend=function(XHR){
    		let access_token=localStorage.getItem("access_token");
    		if(access_token){
    			XHR.setRequestHeader("Authorization","Bearer "+access_token);
    		}
    		beforeSendCallback && beforeSendCallback(XHR);
    	}
	    // 发送网络请求
	    ajax(options);
	  }

	Object.defineProperty($, 'ajax', { value: ajaxProxy });
	const postProxy =function(url, data, callback){
			if ($.isFunction( data ) ) {
				callback = data;
				data = undefined;
			}
			return jQuery.ajax(jQuery.extend( {
				type: "post",
				contentType:"application/json",
				dataType:"json",
				url: url,
				data: typeof data=='object'?JSON.stringify(data):data,
				success: callback
			}, jQuery.isPlainObject( url ) && url ) );
		}
	Object.defineProperty($, 'post', { value: postProxy });
    $.extend({
    	
    });
    
})(jQuery,jQuery.ajax);

	


domain="/";
sys_version=170921;
/*$.post("/authenticated/property/SYS_VERSION",null,function(result){
	if(result.status==200){
		sys_version=result.data;
	}
});*/
var _mask='<div id="window-mmask" class="window-mmask" ><div class="window-mmask-msg" >加载中,请稍候...</div></div>';
//document.onreadystatechange = onDocumentComplete;
//加载状态为complete时移除loading效果
function onDocumentComplete() {
  if (document.readyState == "complete") {
	$('#window-mmask').remove();
  }
}
function mask(){
	$(document.body).append(_mask);
}
$.parser.onComplete=function(){
	$('#window-mmask').remove();
};
sessionuser={};//登录用户信息
function initsessioninfo(callback){
	//取登录用户信息
	$.post("/authenticated/user/sessionuser",{},function(result){
		if(result.success){
			sessionuser=result.data;
			if(callback){
				callback();
			}
		}	
	});
}
function gridSelectRow(grid,callback){
	var selectRows=grid.datagrid('getSelections');
	if(selectRows.length>0){
		callback(selectRows[0]);
	}else{
		info("请选择一条数据！");
	}
}
//document ready
$(function(){
	windowHeight=$(window).height();//窗口高度
});
function info(message){
	$.messager.show({
		title:'提示',
		msg:message,
		timeout:1500,
		showType:'fade',
		style:{
			right:'',
			top:document.body.scrollTop+document.documentElement.scrollTop,
			bottom:''
		}
	});
}
/**
 * 关闭panel
 */
function closeDialog(dialogid){
	$('#'+dialogid).dialog('close');
}
function guid() {
	function s4() {
	    return Math.floor((1 + Math.random()) * 0x10000)
	      .toString(16)
	      .substring(1);
	}
	//return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
	return s4() + s4()  + s4()  + s4()  + s4()  + s4() + s4() + s4();
}

/**
 * 得到Comobox值
 * @param field
 * @param value
 * @returns
 */
function getComoboxValue(field,value){
	var text;
	$.each(comboboxDatas[field],function(i,v){
		if(v.code_value==value){
			text= v.code_name;
			return;
		}
	});
	return text;
}
/**
 * 得到Comotree值
 * @param field
 * @param value
 * @returns
 */
function getCombotreeValue(field,value){
	var text;
	$.each(comboboxDatas[field],function(i,v){
		if(v.id==value){
			text= v.text;
			return;
		}
	});
	return text;
}
/**
 * 根据parent_id重新组装array格式，
 * 带children节点
 * @param node
 * @param array
 */
function insertToArray(node,array,idField,parentIdField){
	if(parentIdField==undefined){
		parentIdField="parent_id";
	}
	if(idField==undefined){
		idField="id";
	}
	$.each(array,function(i,v){
		if(node[parentIdField]==v[idField]){
			if(v.children){
				v.children.push(node);
			}else{
				v.children=new Array();
				v.state='closed';
				v.children.push(node);
			}
			return;
		}
		if(v.children){
			insertToArray(node,v.children,idField,parentIdField);
		}
	});
}
/**
 * 转化成combotree的格式
 * @param sourceArray
 * @returns {Array}
 */
function transformCombotreeArray(sourceArray,idField,parentIdField){
	var newArray=new Array();
	var arrayClone=new Array();
	arrayClone=arrayClone.concat(sourceArray);
	if(parentIdField==undefined){
		parentIdField="parent_id";
	}
	$.each(arrayClone,function(i,v){
		//||v[parentIdField]=="0"
		if(v[parentIdField]==0||v[parentIdField]==undefined){
			newArray.push(v);
		}else{
			insertToArray(v,newArray,idField,parentIdField)
		}
	});
	return newArray;
}
function gridConfirm(grid,message,callback){
	var selectRows=grid.datagrid('getSelections');
	if(selectRows.length>0){
		$.messager.confirm('操作确认', message,function(r){
			if(r)
				callback(selectRows[0]);
		});
	}else{
		$.messager.alert("提示", "请选择一条数据！");
	}
}

